import sys
import os
import logging
import time
import platform
import json
import re
sys.path.append(os.path.join(os.path.dirname(__file__)))
from rpc.rpc_client import RPCClientWrapper
system = platform.system()

global app_path

if getattr(sys, 'frozen', False):  # 检查是否已打包为可执行文件
    app_path = os.path.dirname(sys.executable)
else:
    app_path = "./"
print(f"app运行路径: {app_path}")

def detect_os():
    system = platform.system()
    if system == "Windows":
        return "Windows"
    elif system == "Darwin":
        return "macOS"
    elif system == "Linux":
        return "Linux"
    else:
        return f"Unknown OS: {system}"

def get_ip(slot) -> str:
    sw1 = str(slot)[-1]
    sw2 = ('00'+str(slot))[-2]
    ip_address = 32 + int(sw2)*16 + int(sw1)
    ip_address ="169.254.1."+str(ip_address)
    logging.info('MASK '+str(sw2)+str(sw1)+'  IP:'+str(ip_address))
    return ip_address

class Rpc(object):
    def __init__(self, ip_tester='169.254.1.32', port_tester='7801',ID=''):
        try:
            self.ip_tester = ip_tester
            if ID != "" and int(ID):
                self.ip_tester = get_ip(ID)
                # logging.info(self.ip_tester)
                # print(self.ip_tester)
            if system =="Windows":
                ret_ping = os.popen('ping -w 4 {}'.format(self.ip_tester))     # -n:counts of ping, -w:wait time, unit:ms
            elif system=="Darwin":
                ret_ping = os.popen('ping -c 2 -i 2 -W 2 {}'.format(self.ip_tester))
            ret_ping_info = ret_ping.read()
            # print(ret_ping_info)
            if "TTL" not in ret_ping_info and "trip" not in ret_ping_info:
                logging.info(f'{self.ip_tester} tester ping fail')
                self.tester = None
                return None
            endpoint_client_tester = {'requester': 'tcp://{}:{}'.format(self.ip_tester, port_tester),
                                      'receiver': 'tcp://{}:{}'.format(self.ip_tester, (int(port_tester) + 10000))}

            self.tester = RPCClientWrapper(endpoint_client_tester)
        except Exception:
            raise

    def ret_tester(self):
        return self.tester

    def call_tester(self, method, *args, **kwargs):
        return self.tester.call(method, *args, **kwargs)

    def get_tester_measure_temp(self):
        try:
            temp = self.call_tester("tmp117.get_temperature")
            return temp
        except Exception as e :
            logging.info(f"{self.ip_tester}:{e}")
        finally:
            pass

    def get_tester_mix_fw_version(self):
        try:
            data_dict = self.call_tester("xavier.fw_version")
            # pattern = re.compile(r'\'MIX_FW_PACKAGE\': \'([A-F0-9\_]+)\'')
            # m = pattern.search(data_str)
            # fw = m.group()
            fw = data_dict["MIX_FW_PACKAGE"]
            logging.info(fw)
            return fw
        except Exception as e :
            logging.info(f"{self.ip_tester}:{e}")
        finally:
            pass

    def send_rpc(self,method, *args, **kwargs):
        try:
            data_dict = self.call_tester(method, *args, **kwargs)
            if method == "server.all_methods":
                absolute_path = os.path.join(app_path, "data.json")
                print(absolute_path)
                with open(absolute_path, 'w', encoding='utf-8') as f:
                    json.dump(data_dict, f, ensure_ascii=False, indent=4)
                return data_dict
            # logging.info(data_dict)
            return data_dict
        except Exception as e :
            logging.info(f"{self.ip_tester}:{e}")
        finally:
            pass

        
        

if __name__ == '__main__':
    # rpc = Rpc(ip_tester='169.254.1.40', port_tester='7801')
    # rpc.call_tester('system.reset')
    # temp = rpc.call_tester("tmp117.get_temperature")
    # print(temp)

    tester = Rpc(ID = "13")
    # print(tester.tester())
    if tester.ret_tester() == None:
        print("123")
    # print(tester)
    # temp = tester.get_tester_measure_temp()
    # print(temp)
    # fw = tester.get_tester_mix_fw_version()
    # print(fw)